package org.pybaldaj.logic;

import java.util.ArrayList;

import javax.management.InvalidAttributeValueException;

public class RectField extends Field {

	public RectField (int a_width, int a_height)
	{
		super(a_width*a_height);
		dimensions = new Dimension2D(a_width, a_height);
	}
	
	class Point2D implements Point {
		
		public Point2D (int a_x, int a_y) throws InvalidAttributeValueException
		{
			if (a_x < 0 || a_y < 0 || a_x > dimensions.getDimension(Dimension2D.WIDTH) || a_y > dimensions.getDimension(Dimension2D.HEIGHT))
				throw new InvalidAttributeValueException("Point is out of field.");
			x = a_x;
			y = a_y;
		}
		
		public int getCoordinate (int index)
		{
			if (index == 0)
			{
				return x;
			}
			else
			{
				return y;
			}
		}
		
		public boolean equals (Point p)
		{
			return p.getCoordinate(Dimension2D.WIDTH) == getCoordinate(Dimension2D.WIDTH) &&
					p.getCoordinate(Dimension2D.HEIGHT) == getCoordinate(Dimension2D.HEIGHT);
		}
		
		public int toIndex ()
		{
			return x+y*dimensions.getDimension(Dimension2D.WIDTH);
		}
		
		public boolean isNeighbour (Point p)
		{
			for (Point n_p : getNeighbours())
			{
				if (p.equals(n_p))
					return true;
			}
			
			return false;
		}
		
		public Point[] getNeighbours ()
		{
			ArrayList<Point> neighbours = new ArrayList<Point>();
			if (x > 0)
			{
				try {
					neighbours.add(new Point2D(x-1, y));
				} catch (InvalidAttributeValueException e) {
					e.printStackTrace();
				}
			}
			if (y > 0)
			{
				try {
					neighbours.add(new Point2D(x, y-1));
				} catch (InvalidAttributeValueException e) {
					e.printStackTrace();
				}
			}
			if (x < dimensions.getDimension(Dimension2D.WIDTH))
			{
				try {
					neighbours.add(new Point2D(x+1, y));
				} catch (InvalidAttributeValueException e) {
					e.printStackTrace();
				}
			}
			if (y < dimensions.getDimension(Dimension2D.HEIGHT))
			{
				try {
					neighbours.add(new Point2D(x, y+1));
				} catch (InvalidAttributeValueException e) {
					e.printStackTrace();
				}
			}
			
			return (Point[]) neighbours.toArray();
		}
		
		int x;
		int y;
	}
	
	class Dimension2D implements Dimensions {
		
		public Dimension2D (int width, int height)
		{
			dims = new int[] {width, height};
		}
		
		public int getDimension(int index) {
			return dims[index];
		}

		public int getDimensionsNum() {
			return 2;
		}
		
		/**
		 * Index of the WIDTH dimension
		 */
		public static final int WIDTH = 0;
		
		/**
		 * Index of the HEIGHT dimension
		 */
		public static final int HEIGHT = 1;
		private int[] dims;
	}
}
